package com.woniu108.person.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu108.carService.commons.log.AdminHistoryLog;
import com.woniu108.carService.commos.dto.StoreApplyDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.*;
import com.woniu108.person.form.AddStoreForm;
import com.woniu108.person.form.ApplyNewStoreForm;
import com.woniu108.person.form.RejectStoreApplyForm;
import com.woniu108.person.form.StoreApplyListForm;
import com.woniu108.person.model.StoreApply;
import com.woniu108.person.param.ApplyNewStoreParam;
import com.woniu108.person.param.RejectStoreApplyParam;
import com.woniu108.person.param.StoreApplyListParam;
import com.woniu108.person.service.StoreApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 门店新增申请表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/storeApply")
@Api(tags = "门店申请信息接口")
public class StoreApplyController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private StoreApplyService storeApplyService;
    @Resource
    private OSSUtil ossUtil;
    @Resource
    private StoreController storeController;

    public String getAdminId(String token) {
        String refreshToken = redisUtil.getString(token);
        String adminId = JWTUtil.parseAdminToken(refreshToken).get("adminId").toString();
        return adminId;
    }

    public String getUserId(String token) {
        String refreshToken = redisUtil.getString(token);
        String userId = JWTUtil.parseUserToken(refreshToken).get("userId").toString();
        return userId;
    }

    public String getStoreAdminId(String token) {
        String refreshToken = redisUtil.getString(token);
        String storeAdminId = JWTUtil.parseStoreAdminToken(refreshToken).get("storeAdminId").toString();
        return storeAdminId;
    }

    /**
     * 新增门店申请,仅门店管理员可提交申请，后台管理员不需要提交申请即可新增门店
     * @param token
     * @param form 门店申请信息
     * @return result 接口是否正常访问到结果
     */
    @PostMapping("/applyNewStore.st")
    @ApiOperation("新增门店申请")
    public Result applyNewStore(@RequestHeader String token, @RequestBody ApplyNewStoreForm form) throws Exception {
        ApplyNewStoreParam param = BeanUtil.toBean(form, ApplyNewStoreParam.class);
        //先判断文件是否为图片类型
        if (form.getStoreImage()!=null&&!FileUtil.isImageFile(form.getStoreImage().getInputStream())) {
            throw new WoniuException("上传文件类型错误，请上传图片", 10001);

        }else if(form.getStoreImage()!=null){
            String oldName = form.getStoreImage().getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf("."));//取文件后缀
            String fileName = UUID.randomUUID().toString();//生成新的图片名称
            String filePath = ossUtil.uploadFile(form.getStoreImage().getInputStream(), fileName + suffix, "aliyunfyl");
            param.setStoreImage(filePath);
        }
        String storeAdminId = this.getStoreAdminId(token);
        if (storeAdminId == null) throw new WoniuException("非门店管理员账号，不可提交申请", 10001);
        StoreApply storeApply = BeanUtil.toBean(param, StoreApply.class);
        storeApply.setApplyState(StaticData.STORE_APPLY_STATE_WAIT);
        storeApply.setStoreAdminId(storeAdminId);
        storeApply.setCreateTime(LocalDateTime.now());
        storeApplyService.save(storeApply);
        return Result.getResult().setMsg("提交新增门店申请成功");
    }

    /**
     * 展示申请列表，门店管理员仅可查看自己的申请，后台管理员可查看全部
     * @param form 门店申请列表筛选条件
     * @param token
     * @return  StoreApplyDto 门店申请详情列表
     */
    @PostMapping("/storeApplyList.c")
    @ApiOperation("门店申请列表")
    public Result<Page<StoreApplyDto>> storeApplyList(@RequestBody StoreApplyListForm form, @RequestHeader String token) {
        StoreApplyListParam param = BeanUtil.toBean(form, StoreApplyListParam.class);
        String adminId = this.getAdminId(token);
        if (adminId == null ) throw new WoniuException("非管理员账号,无权查看", 10001);
        Page<StoreApplyDto> page = storeApplyService.storeApplyList(param);
        return Result.newPageInstance(StoreApplyDto.class).setData(page);
    }

    /**
     * 展示申请列表中未审核的申请,功能仅管理员可用
     * @param form 门店申请列表筛选条件
     * @param token
     * @return  StoreApplyDto 门店申请详情列表
     */
    @PostMapping("/storeApplyListStateNormal.c")
    @ApiOperation("门店申请待处理列表")
    public Result<Page<StoreApplyDto>> storeApplyListStateNormal(@RequestBody StoreApplyListForm form, @RequestHeader String token) {
        StoreApplyListParam param = BeanUtil.toBean(form, StoreApplyListParam.class);
        String adminId = this.getAdminId(token);
        if (adminId == null ) throw new WoniuException("非管理员账号,无权查看", 10001);
        Page<StoreApplyDto> page = storeApplyService.storeApplyListStateNormal(param);
        return Result.newPageInstance(StoreApplyDto.class).setData(page);
    }

    /**
     * 展示申请列表中已审核的申请(含通过、已驳回),功能仅管理员可用
     * @param form 门店申请列表筛选条件
     * @param token
     * @return  StoreApplyDto 门店申请详情列表
     */
    @PostMapping("/storeApplyListStateDealed.c")
    @ApiOperation("门店申请已处理列表")
    public Result<Page<StoreApplyDto>> storeApplyListStateDealed(@RequestBody StoreApplyListForm form, @RequestHeader String token) {
        StoreApplyListParam param = BeanUtil.toBean(form, StoreApplyListParam.class);
//        String adminId = this.getAdminId(token);
//        if (adminId == null ) throw new WoniuException("非管理员账号,无权查看", 10001);
        Page<StoreApplyDto> page = storeApplyService.storeApplyListStateDealed(param);
        return Result.newPageInstance(StoreApplyDto.class).setData(page);
    }
    /**
     * 展示申请列表，门店管理员仅可查看自己的申请
     * @param form 门店申请列表筛选条件
     * @param token
     * @return  StoreApplyDto 门店申请详情列表
     */
    @PostMapping("/storeApplyListByStoreAdmin.st")
    @ApiOperation("门店申请列表")
    public Result<Page<StoreApplyDto>> storeApplyListByStoreAdmin(@RequestBody StoreApplyListForm form, @RequestHeader String token) {
        StoreApplyListParam param = BeanUtil.toBean(form, StoreApplyListParam.class);
        String storeAdminId = this.getStoreAdminId(token);
        if (storeAdminId == null) throw new WoniuException("非门店管理员,无权查看", 10001);
        param.setStoreAdminId(storeAdminId);
        Page<StoreApplyDto> page = storeApplyService.storeApplyList(param);
        return Result.newPageInstance(StoreApplyDto.class).setData(page);
    }

    /**
     * 通过新增门店申请
     * @param storeApplyId 门店申请信息ID
     * @param token
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/allowStoreApply.api")
    @ApiOperation("通过新增门店申请")
    @ApiImplicitParam(name = "storeApplyId",value ="门店申请ID" )
    @AdminHistoryLog
    public Result allowStoreApply(Integer storeApplyId, @RequestHeader String token) {
        StoreApply storeApply = storeApplyService.getById(storeApplyId);
        if (storeApply.getApplyState() != StaticData.STORE_APPLY_STATE_WAIT) throw new WoniuException("申请状态异常", 10001);
        AddStoreForm form = BeanUtil.toBean(storeApply, AddStoreForm.class);
        Result result = storeController.addStore(form, token);
        if (result.getCode() != 200) throw new WoniuException(result.getMsg(), result.getCode());
        storeApply.setApplyState(StaticData.STORE_APPLY_STATE_ALLOW);
        storeApplyService.updateById(storeApply);
        return Result.getResult().setMsg("通过申请成功");
    }

    /**
     * 驳回门店新增申请
     * @param form 驳回信息 申请ID 驳回理由
     * @return result 接口是否正常访问到结果
     */
    @PostMapping("/rejectStoreApply.api")
    @ApiOperation("驳回门店新增申请")
    @AdminHistoryLog
    public Result rejectStoreApply(@RequestBody RejectStoreApplyForm form) {
        RejectStoreApplyParam param = BeanUtil.toBean(form, RejectStoreApplyParam.class);
        StoreApply storeApply = storeApplyService.getById(param.getStoreApplyId());
        if (storeApply.getApplyState() != StaticData.STORE_APPLY_STATE_WAIT) throw new WoniuException("申请状态异常", 10001);
        storeApply.setReason(param.getReason());
        storeApply.setApplyState(StaticData.STORE_APPLY_STATE_NOT_ALLOW);
        storeApplyService.updateById(storeApply);
        return Result.getResult().setMsg("驳回申请成功");
    }

    /**
     * 删除申请记录 (伪删除)
     * @param token
     * @param StoreApplyId 门店申请ID
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/deleteStoreApply.api")
    @ApiOperation("删除申请记录")
    @AdminHistoryLog
    @ApiImplicitParam(name = "storeApplyId",value ="门店申请ID" )
    public Result deleteStoreApply(@RequestHeader String token, Integer StoreApplyId) {
        String adminId = this.getAdminId(token);
        StoreApply storeApply = storeApplyService.getById(StoreApplyId);
        if (adminId == null) throw new WoniuException("非管理员账号,无权操作", 10001);
        storeApply.setApplyState(StaticData.STORE_APPLY_STATE_DELETE);
        storeApplyService.updateById(storeApply);
        //删除oss云端文件
        ossUtil.deleteFile("aliyunfyl", storeApply.getStoreImage());
        return Result.getResult().setMsg("删除申请记录成功");
    }

    /**
     * 删除申请记录 (伪删除)
     * @param token
     * @param StoreApplyId 门店申请ID
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/deleteStoreApplyByStoreAdmin.st")
    @ApiOperation("删除申请记录")
    @ApiImplicitParam(name = "storeApplyId",value ="门店申请ID" )
    public Result deleteStoreApplyByStoreAdmin(@RequestHeader String token, Integer StoreApplyId) {
        String storeAdminId = this.getStoreAdminId(token);
        StoreApply storeApply = storeApplyService.getById(StoreApplyId);
        if (!storeAdminId.equals(storeApply.getStoreAdminId()))
            throw new WoniuException("非本账号发出的申请,不可删除", 10001);
        if (storeAdminId == null) throw new WoniuException("非门店管理员账号,无权操作", 10001);
        storeApply.setApplyState(StaticData.STORE_APPLY_STATE_DELETE);
        storeApplyService.updateById(storeApply);
        //删除oss云端文件
        ossUtil.deleteFile("aliyunfyl", storeApply.getStoreImage());
        return Result.getResult().setMsg("删除申请记录成功");
    }
}
